package com.zhongkai.service.impl;

import com.mysql.jdbc.StringUtils;
import com.zhongkai.Arith;
import com.zhongkai.Bean.AssetBean;
import com.zhongkai.Bean.PageBean;
import com.zhongkai.app.service.IBaseDao;
import com.zhongkai.app.service.PageQuerDao;
import com.zhongkai.app.service.SumService;
import com.zhongkai.model.utils.ZhongkaiResult;
import com.zhongkai.model3.SumRecord;
import com.zhongkai.model3.ZkAsset;
import com.zhongkai.model3.ZkTally;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.joda.time.DateTime;
import org.joda.time.Instant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class SumServiceImpl implements SumService {

    @Autowired
    private IBaseDao iBaseDao;


    @Autowired
    private PageQuerDao pageQuerDao;


    /**
     * 获取公司资产情况
     */
    @Override
    public ZhongkaiResult getAsset() {


        ZkAsset zkAsset = (ZkAsset) iBaseDao.get("from ZkAsset za where za.assetType='0'");
        DateTime dateTime = new DateTime();

        if (zkAsset == null) {
            long millis = dateTime.getMillis(); //获取当前系统时间戳
            zkAsset = new ZkAsset();

            zkAsset.setAssetName("现金");
            zkAsset.setAssetElite("现金初始化");
            zkAsset.setAssetSum("0");
            zkAsset.setAssetTime(millis);
            zkAsset.setNewTime(millis);
            zkAsset.setAssetType("0");
            iBaseDao.save(zkAsset);
        }
        AssetBean assetBean = new AssetBean(); //页面实体bean

        ZkAsset zkAssets = (ZkAsset) iBaseDao.get("from ZkAsset za where za.assetType='0'");//现金

        List<ZkAsset> ys_list = iBaseDao.find("from ZkAsset za where za.assetType='1'");//全部应收款 和已收款

        List<ZkAsset> ygf_list = iBaseDao.find("from ZkAsset za where za.assetType='2'");//应付款

        String sum_all = "0";
        Long max_time = 0L;


        if (ys_list.size() != 0) {
            for (ZkAsset asset : ys_list) {  //取出应收款的钱 相加
                sum_all = Arith.add(sum_all, asset.getAssetSum());
                if (asset.getAssetTime() > max_time) {
                    max_time = asset.getAssetTime();
                }
            }
        }


        assetBean.setCash_ys(sum_all); //应收款

        assetBean.setCash(zkAssets.getAssetSum()); //全部现金
        assetBean.setCa_time(new DateTime(zkAssets.getAssetTime()).toString("yyyy-MM-dd HH:mm:ss"));  //现金修改时间
        if (max_time.toString().equals("0")) {
            assetBean.setYs_time("暂未添加");
        } else {
            assetBean.setYs_time(new DateTime(max_time).toString("yyyy-MM-dd HH:mm:ss"));  //应收款修改时间
        }

        //max_time


        sum_all = Arith.add(sum_all, zkAssets.getAssetSum()); //加上现金 这是全部资产
        assetBean.setSum_all(sum_all); //全部资产


        String yf_all = "0";
        Long max_time2 = 0L;
        if (ygf_list.size() != 0) {
            for (ZkAsset asset : ygf_list) { //应付款相加
                yf_all = Arith.add(yf_all, asset.getAssetSum());
                if (asset.getAssetTime() > max_time2) {
                    max_time2 = asset.getAssetTime();
                }
            }
        }

        assetBean.setCash_yf(yf_all); //全部应付款
        if (max_time2.toString().equals("0")) {
            assetBean.setYf_time("暂未添加");
        } else {
            assetBean.setYf_time(new DateTime(max_time2).toString("yyyy-MM-dd HH:mm:ss"));  //应付款修改时间
        }




        String sum_j = Arith.sub(sum_all, yf_all); //全部资产减去应付款 等于净资产
        assetBean.setSum_j(sum_j);//净资产
        assetBean.setSum_f(yf_all); //负债为全部应付款

        return ZhongkaiResult.ok(assetBean);
    }


    /**
     * 修改金额
     *
     * @param sum         金额
     * @param updata_name 修改者
     * @param asset_elite 摘要信息
     */
    @Override
    public ZhongkaiResult updataSum(String sum, String updata_name, String asset_elite) {
        if (StringUtils.isNullOrEmpty(sum) || StringUtils.isNullOrEmpty(updata_name)
                || StringUtils.isNullOrEmpty(asset_elite))

        {
            return ZhongkaiResult.build(400, "数据不完整");
        }


        ZkAsset zkAsset = (ZkAsset) iBaseDao.get("from ZkAsset za where za.assetType='0'");
        DateTime dateTime = new DateTime();
        long millis = dateTime.getMillis(); //获取当前系统时间戳
        if (zkAsset == null) {

            zkAsset = new ZkAsset();

            zkAsset.setAssetName("现金");
            zkAsset.setAssetElite(asset_elite);
            zkAsset.setAssetSum(sum);
            zkAsset.setAssetTime(millis);
            zkAsset.setNewTime(millis);
            zkAsset.setAssetType("0");
            iBaseDao.save(zkAsset);
        } else {
            zkAsset.setAssetTime(millis); //现金修改时间
            zkAsset.setAssetSum(sum);
            zkAsset.setAssetElite(asset_elite);
            iBaseDao.update(zkAsset);
        }


        SumRecord sumRecord = new SumRecord();
        sumRecord.setOperateType("现金");
        sumRecord.setCzZy(asset_elite);
        sumRecord.setSjSum(sum);
        sumRecord.setCzJl("修改现金金额");
        sumRecord.setNewTime(millis);
        sumRecord.setCzName(updata_name);
        iBaseDao.save(sumRecord);
        return ZhongkaiResult.ok();
    }


    /**
     * 新增应收款项
     *
     * @param asset_name  款项名称
     * @param asset_elite 摘要信息
     * @param asset_sum   涉及到的金额
     * @param asset_time  预计回款时间
     */
    @Override
    public ZhongkaiResult addMinusSum(String asset_name, String asset_elite, String asset_sum, Long asset_time, String name) {
        if (StringUtils.isNullOrEmpty(asset_name) || StringUtils.isNullOrEmpty(asset_elite)
                || StringUtils.isNullOrEmpty(asset_sum) || StringUtils.isNullOrEmpty(name))

        {
            return ZhongkaiResult.build(400, "数据不完整");
        }

        DateTime dateTime = new DateTime();
        long millis = dateTime.getMillis(); //获取当前系统时间戳

        ZkAsset zkAsset = new ZkAsset();

        zkAsset.setAssetName(asset_name);
        zkAsset.setAssetElite(asset_elite);
        zkAsset.setAssetSum(asset_sum);
        zkAsset.setAssetTime(asset_time); //回款时间
        zkAsset.setNewTime(millis);
        zkAsset.setAssetType("1");

        iBaseDao.save(zkAsset);


        SumRecord sumRecord = new SumRecord();
        sumRecord.setOperateType(asset_name);
        sumRecord.setCzZy(asset_elite);
        sumRecord.setSjSum(asset_sum);
        sumRecord.setCzJl("新增应收款");
        sumRecord.setNewTime(millis);
        sumRecord.setCzName(name);
        iBaseDao.save(sumRecord);

        return ZhongkaiResult.ok();
    }


    /**
     * 新增应付款项
     *
     * @param asset_name  款项名称
     * @param asset_elite 摘要信息
     * @param asset_sum   涉及到的金额
     * @param asset_time  预计付款时间
     */
    @Override
    public ZhongkaiResult addPayOut(String asset_name, String asset_elite, String asset_sum, Long asset_time, String name) {
        if (StringUtils.isNullOrEmpty(asset_name) || StringUtils.isNullOrEmpty(asset_elite)
                || StringUtils.isNullOrEmpty(asset_sum) || StringUtils.isNullOrEmpty(name))

        {
            return ZhongkaiResult.build(400, "数据不完整");
        }

        DateTime dateTime = new DateTime();
        long millis = dateTime.getMillis(); //获取当前系统时间戳

        ZkAsset zkAsset = new ZkAsset();

        zkAsset.setAssetName(asset_name);
        zkAsset.setAssetElite(asset_elite);
        zkAsset.setAssetSum(asset_sum);
        zkAsset.setAssetTime(asset_time); //回款时间
        zkAsset.setNewTime(millis);
        zkAsset.setAssetType("2");

        iBaseDao.save(zkAsset);


        SumRecord sumRecord = new SumRecord();
        sumRecord.setOperateType(asset_name);
        sumRecord.setCzZy(asset_elite);
        sumRecord.setSjSum(asset_sum);
        sumRecord.setCzJl("新增应付款");
        sumRecord.setNewTime(millis);
        sumRecord.setCzName(name);
        iBaseDao.save(sumRecord);

        return ZhongkaiResult.ok();
    }


    /**
     * 获取资产列表
     *
     * @param asseet_type 1回款  2待付款
     */
    @Override
    public ZhongkaiResult getAssetList(String asseet_type, Integer page, Integer rows) {
        try {
            PageBean pageBean = new PageBean();
            pageBean.setCurrentPage(page);
            pageBean.setPageSize(rows);
            DetachedCriteria detachedCriteria = DetachedCriteria.forClass(ZkAsset.class);
            detachedCriteria.add(Restrictions.eq("assetType", asseet_type)); //增加条件
            detachedCriteria.addOrder(Order.asc("newTime")); //根据传入的字段进行升序排序
            pageBean.setDetachedCriteria(detachedCriteria);
            pageQuerDao.pageQuery(pageBean);
            return ZhongkaiResult.ok(pageBean);
        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(405, "查询失败");
        }
    }

    //--------------------------------------------------------------------------


    /**
     * 新增记账
     *
     * @param tally_type  类型 0支出  1收入
     * @param time        产生时间
     * @param sum         金额
     * @param asset_elite 摘要信息
     * @param name        操作者
     */
    @Override
    public ZhongkaiResult addTally(String tally_type, Long time, String sum, String asset_elite, String name) {
        if (StringUtils.isNullOrEmpty(tally_type) || StringUtils.isNullOrEmpty(sum)
                || StringUtils.isNullOrEmpty(asset_elite) || StringUtils.isNullOrEmpty(name))

        {
            return ZhongkaiResult.build(400, "数据不完整");
        }

        ZkTally zkTally = new ZkTally();

        zkTally.setTallyType(tally_type); //类型
        zkTally.setNewTime(time);  //设置的时间
        DateTime dateTime = new DateTime(time);  //得到具体日期
        zkTally.setTallyTime(dateTime.toString("yyyy-MM-dd"));
        zkTally.setTallyReason(asset_elite); //记账摘要
        zkTally.setTallySum(sum);


        ZkAsset zkAsset = (ZkAsset) iBaseDao.get("from ZkAsset za where za.assetType='0'");


        if ("0".equals(tally_type)) {
            String new_sum = Arith.sub(zkAsset.getAssetSum(), sum); //新增支出 减法

            zkAsset.setAssetTime(Instant.now().getMillis());
            zkAsset.setAssetSum(new_sum);

            SumRecord sumRecord = new SumRecord();
            sumRecord.setOperateType("现金");
            sumRecord.setCzZy(asset_elite);
            sumRecord.setSjSum(sum);
            sumRecord.setCzJl("增加支出");
            sumRecord.setNewTime(Instant.now().getMillis());
            sumRecord.setCzName(name);
            iBaseDao.save(sumRecord);

        } else {
            String new_sum = Arith.add(zkAsset.getAssetSum(), sum); //新增收入  //加法

            zkAsset.setAssetTime(Instant.now().getMillis());
            zkAsset.setAssetSum(new_sum);

            SumRecord sumRecord = new SumRecord();
            sumRecord.setOperateType("现金");
            sumRecord.setCzZy(asset_elite);
            sumRecord.setSjSum(sum);
            sumRecord.setCzJl("增加盈收");
            sumRecord.setNewTime(Instant.now().getMillis());
            sumRecord.setCzName(name);
            iBaseDao.save(sumRecord);
        }

        iBaseDao.update(zkAsset);
        iBaseDao.save(zkTally);

        return ZhongkaiResult.ok();
    }


    /**
     * 修改记账
     *
     * @param tally_type  类型 0支出  1收入
     * @param time        产生时间
     * @param sum         金额
     * @param asset_elite 摘要信息
     * @param name        操作者
     */
    @Override
    public ZhongkaiResult updataTally(Long id, String tally_type, Long time, String sum, String asset_elite, String name) {
        if (StringUtils.isNullOrEmpty(tally_type) || StringUtils.isNullOrEmpty(sum)
                || StringUtils.isNullOrEmpty(asset_elite) || StringUtils.isNullOrEmpty(name))

        {
            return ZhongkaiResult.build(400, "数据不完整");
        }
        ZkTally zkTally = (ZkTally) iBaseDao.get("from ZkTally zt there zt.id=" + id);

        if (zkTally == null) {
            return ZhongkaiResult.build(400, "数据不存在");
        }

        ZkAsset zkAsset = (ZkAsset) iBaseDao.get("from ZkAsset za where za.assetType='0'");
        String new_sum;

        if ("0".equals(zkTally.getTallyType())) {
            new_sum = Arith.add(zkAsset.getAssetSum(), zkTally.getTallySum()); //加法 回复恢复支出
        } else {
            new_sum = Arith.sub(zkAsset.getAssetSum(), zkTally.getTallySum()); //减法 恢复收入
        }


        SumRecord sumRecord = new SumRecord();
        if ("0".equals(tally_type)) { //支出
            new_sum = Arith.sub(new_sum, sum); //减法 修改成支出

            sumRecord.setOperateType("现金");
            sumRecord.setCzZy(asset_elite);
            sumRecord.setSjSum(sum);
            sumRecord.setCzJl("修改支出记录");
            sumRecord.setNewTime(Instant.now().getMillis());
            sumRecord.setCzName(name);
        } else { //收入
            new_sum = Arith.add(new_sum, sum); //加法 修改成收入
            sumRecord.setOperateType("现金");
            sumRecord.setCzZy(asset_elite);
            sumRecord.setSjSum(sum);
            sumRecord.setCzJl("修改盈收记录");
            sumRecord.setNewTime(Instant.now().getMillis());
            sumRecord.setCzName(name);
        }

        zkAsset.setAssetTime(Instant.now().getMillis());
        zkAsset.setAssetSum(new_sum);


        iBaseDao.update(zkAsset);
        iBaseDao.save(sumRecord);

        zkTally.setTallyType(tally_type);
        zkTally.setNewTime(time);  //设置的时间
        DateTime dateTime = new DateTime(time);  //得到具体日期
        zkTally.setTallyTime(dateTime.toString("yyyy-MM-dd"));
        zkTally.setTallyReason(asset_elite); //记账摘要
        zkTally.setTallySum(sum);

        iBaseDao.update(zkTally);
        return ZhongkaiResult.ok();
    }

    @Override
    public ZhongkaiResult deleteTally(Long id, String name) {

        if (StringUtils.isNullOrEmpty(name))

        {
            return ZhongkaiResult.build(400, "数据不完整");
        }

        ZkTally zkTally = (ZkTally) iBaseDao.get("from ZkTally zt there zt.id=" + id);

        if (zkTally == null) {
            return ZhongkaiResult.build(400, "数据不存在");
        }


        ZkAsset zkAsset = (ZkAsset) iBaseDao.get("from ZkAsset za where za.assetType='0'");
        SumRecord sumRecord = new SumRecord();
        if ("0".equals(zkTally.getTallyType())) {  //删除支出  现金增加
            String new_sum = Arith.add(zkAsset.getAssetSum(), zkTally.getTallySum()); //加法 删除支出
            zkAsset.setAssetTime(Instant.now().getMillis());
            zkAsset.setAssetSum(new_sum);


            sumRecord.setOperateType("现金");
            sumRecord.setCzZy("删除支出,现金增加");
            sumRecord.setSjSum(zkTally.getTallySum());
            sumRecord.setCzJl("删除支出");
            sumRecord.setNewTime(Instant.now().getMillis());
            sumRecord.setCzName(name);
            //  iBaseDao.save(sumRecord);
        } else { //删除收入
            String new_sum = Arith.sub(zkAsset.getAssetSum(), zkTally.getTallySum()); //删除收入  减法
            zkAsset.setAssetTime(Instant.now().getMillis());
            zkAsset.setAssetSum(new_sum);


            sumRecord.setOperateType("现金");
            sumRecord.setCzZy("删除收入,现金减少");
            sumRecord.setSjSum(zkTally.getTallySum());
            sumRecord.setCzJl("删除收入");
            sumRecord.setNewTime(Instant.now().getMillis());
            sumRecord.setCzName(name);

        }

        iBaseDao.save(sumRecord);
        iBaseDao.delete(zkTally);
        iBaseDao.update(zkAsset);

        return ZhongkaiResult.ok();
    }

    @Override
    public ZhongkaiResult getOperationDate(Integer page, Integer rows) {

        PageBean pageBean = new PageBean();
        pageBean.setCurrentPage(page);
        pageBean.setPageSize(rows);
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(SumRecord.class);
       // detachedCriteria.addOrder(Order.asc("newTime")); //根据传入的字段进行升序排序
        detachedCriteria.addOrder(Order.desc("newTime")); //排序
        pageBean.setDetachedCriteria(detachedCriteria);
        pageQuerDao.pageQuery(pageBean);
        return ZhongkaiResult.ok(pageBean);
    }
}
